<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.bootcdn.net/ajax/libs/pubsub-js/1.9.4/pubsub.min.js"></script>
    <script src="./src/vue.js"></script>
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="show=!show">显示/隐藏</button>
      <father-com v-show="show"></father-com>
    </div>
    <template id="fatherCom">
      <div>
        <h3>父组件</h3>
        <p>name: {{name}}</p>
        <hr />
        <son-com></son-com>
      </div>
    </template>
    <template id="sonCom">
      <div>
        <h3>子组件</h3>
        <button @click="sendData">发布事件</button>
      </div>
    </template>
    <script>
      const sonCom = {
        template: "#sonCom",
        methods: {
          sendData() {
            PubSub.publish("getName", "小明");
          },
        },
      };
      const fatherCom = {
        template: "#fatherCom",
        data() {
          return {
            name: "",
            eventID: 0,
          };
        },
        created() {
          // 提前订阅事件
          this.eventID = PubSub.subscribe("getName", (msg, data) => {
            console.log(msg, data);
            this.name = data;
          });
        },
        beforeDestory() {
          // 取消订阅，防止重复订阅。
          PubSub.unsubscribe(this.eventID);
        },
        components: {
          sonCom,
        },
      };
      const vm = new Vue({
        el: "#app",
        data: {
          show: true,
        },
        components: {
          fatherCom,
        },
      });
    </script>
  </body>
</html>
